import axios from 'axios';
import { storage } from './storage';

if (!window.location.origin) {
  window.location.origin = `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}`;
}

const instance = axios.create({
  baseURL: 'http://hrcs-xz.top/epay'
});
let reqConfig;

instance.interceptors.request.use(
  (config) => {
    reqConfig = config;
    reqConfig.headers.token = storage.get('token');
    if (!reqConfig.data) {
      reqConfig.data = {};
    }
    if (!reqConfig.params) reqConfig.params = {};
    return reqConfig;
  },
  error => Promise.reject(error),
);

instance.interceptors.response.use((response) => {
  if (response.data.code === 408) {
    window.location = '/login';
    return;
  }
  return response;
});

export default instance;